#include <semaphore.h>
#include <pthread.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define NUM 5

sem_t blank, star;
int queue[NUM];


void* Consumer(void* arg)
{
	int i = 0;
	while(1){
	sem_wait(&star);

	printf("consumer: %d\n", queue[i]);
	queue[i] = 0;	
	
	sem_post(&blank);

	i = (i+1)%NUM;
	
	sleep((rand()+1)%3);}
	
	return NULL;
}

void* Producer(void* arg)
{
	int i = 0;
	while(1){
	sem_wait(&blank);

	queue[i] = (rand()+1)%100;
	printf("--------------producer: %d\n", queue[i]);

	sem_post(&star);

	i = (i+1)%NUM;

	sleep((rand()+1)%3);}

	return NULL;
}


int main()
{
	pthread_t cid, pid;

	srand(time(NULL));

	sem_init(&blank, 0, NUM);
	sem_init(&star, 0, 0);
	
	pthread_create(&cid, NULL, Consumer, NULL);
	pthread_create(&pid, NULL, Producer, NULL);

	pthread_join(cid, NULL);
	pthread_join(pid, NULL);
	
	sem_destroy(&blank);
	sem_destroy(&star);
	pthread_exit(NULL);
}
